interface MindMapData {
  id: string
  type: 'topic' | 'topic-branch' | 'topic-child'
  label: string
  width: number
  height: number
  children?: MindMapData[]
}

interface TreeNode {
  id: string
  label: string
  children: TreeNode[]
}

let nodeIdCounter = 0

/**
 * 生成唯一的节点 ID
 * @returns {string} 唯一的节点 ID
 */
function generateNodeId(): string {
  console.debug('[MermaidParser] 生成新节点ID，当前计数器:', nodeIdCounter);
  
  try {
    // 检查计数器是否有效
    if (typeof nodeIdCounter !== 'number' || isNaN(nodeIdCounter) || nodeIdCounter < 0) {
      console.warn('[MermaidParser] 节点ID计数器无效，重置为0');
      nodeIdCounter = 0;
    }

    // 防止计数器溢出
    if (nodeIdCounter >= Number.MAX_SAFE_INTEGER - 1) {
      console.warn('[MermaidParser] 节点ID计数器接近最大值，重置为0');
      nodeIdCounter = 0;
    }

    const newId = `node-${++nodeIdCounter}`;
    console.debug('[MermaidParser] 生成的新节点ID:', newId);
    return newId;
    
  } catch (error) {
    console.error('[MermaidParser] 生成节点ID时发生错误:', error);
    // 返回一个安全的回退ID
    return `fallback-node-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  }
}

/**
 * 解析 Mermaid 格式的思维导图文本
 * @param {string} text Mermaid 格式的文本
 * @returns {TreeNode} 树形结构的节点数据
 */
export function parseMermaidToTree(text: string): TreeNode {
  console.debug('[MermaidParser] Starting to parse mermaid text...');
  
  try {
    // 输入验证
    if (!text || typeof text !== 'string') {
      console.error('[MermaidParser] Invalid input: text is empty or not a string');
      throw new Error('Invalid input: Mermaid text must be a non-empty string');
    }

    console.debug('[MermaidParser] Input text:', text.substring(0, 100) + (text.length > 100 ? '...' : ''));
    console.debug('[MermaidParser] Input length:', text.length);
    
    // Reset node ID counter
    nodeIdCounter = 0;

    // Normalize line endings and split
    const lines = text.replace(/\r\n/g, '\n').trim().split('\n');
    console.debug(`[MermaidParser] Total lines: ${lines.length}`);

    // 验证是否包含mindmap关键字
    const hasMindmapKeyword = lines.some(line => line.trim().toLowerCase() === 'mindmap');
    if (!hasMindmapKeyword) {
      console.warn('[MermaidParser] Warning: Missing "mindmap" keyword in input');
    }
  
    let root: TreeNode | null = null;
    const stack: Array<{ node: TreeNode; level: number }> = [];
    let currentIndentBase = 0; // 当前层级的基准缩进
    
    // 修复：将内部的 try 块移到外部 try 块内部
    for (let lineNumber = 0; lineNumber < lines.length; lineNumber++) {
      try {
        const originalLine = lines[lineNumber];
        console.debug(`\n处理第 ${lineNumber + 1} 行: "${originalLine}"`);
        
        // 获取当前行的缩进和内容
        const indentMatch = originalLine.match(/^(\s*)/);
        const indent = indentMatch ? indentMatch[1].length : 0;
        const content = originalLine.trim();

        console.debug(`缩进长度: ${indent}, 内容: "${content}"`);

        // 跳过空行和mindmap关键字行
        if (!content || content.toLowerCase() === 'mindmap') {
          console.debug('跳过空行或mindmap关键字行');
          continue;
        }

        // 清理标签内容
        let cleanedLabel = cleanNodeLabel(content);

        // 如果清理后的内容为空，跳过
        if (!cleanedLabel.trim()) {
          console.debug('清理后标签内容为空，跳过此行');
          continue;
        }

        const node: TreeNode = {
          id: generateNodeId(),
          label: cleanedLabel,
          children: []
        };

        if (!root) {
          // 第一个有效行作为根节点
          root = node;
          stack.push({ node, level: 0 });
          currentIndentBase = indent;
          console.debug('设置根节点:', { id: node.id, label: node.label, level: 0 });
          continue;
        }

        // 计算当前行的层级
        // 根节点的缩进作为基准缩进，子节点的层级通过缩进差值计算
        const level = indent > currentIndentBase ? Math.floor((indent - currentIndentBase) / 2) + 1 : 1;
        
        // 回溯到正确的父节点层级
        while (stack.length > 0 && stack[stack.length - 1].level >= level) {
          stack.pop();
        }

        if (stack.length === 0) {
          console.warn(`[MermaidParser] Warning: Line ${lineNumber + 1} has unexpected indentation, treating as child of root`);
          stack.push({ node: root, level: 0 });
        }

        const parent = stack.length > 0 ? stack[stack.length - 1].node : root;

        // 添加到父节点
        console.debug(`添加节点 ${node.label} 到父节点 ${parent.label}，层级: ${level}`);
        parent.children.push(node);
        stack.push({ node, level });
      } catch (lineError) {
        console.error(`[MermaidParser] Error processing line ${lineNumber + 1}:`, lineError);
        console.warn(`[MermaidParser] Skipping problematic line and continuing...`);
        // 继续处理下一行，不中断整个解析过程
      }
    }

    if (!root) {
      console.error('[MermaidParser] 无效的思维导图: 未找到根节点');
      throw new Error('Invalid mindmap: no root node found');
    }

    console.debug('[MermaidParser] 解析完成，生成的树结构:', {
      rootId: root.id,
      rootLabel: root.label,
      childrenCount: root.children.length
    });

    return root;
  } catch (error) {
    console.error('[MermaidParser] 解析思维导图时发生错误:', error);
    
    // 创建一个错误节点作为回退
    const errorRoot: TreeNode = {
      id: 'error-root',
      label: '解析错误',
      children: [{
        id: 'error-details',
        label: error instanceof Error ? error.message : '未知解析错误',
        children: []
      }]
    };
    
    return errorRoot;
  }
}

/**
 * 清理节点标签内容，移除特殊符号、注释等
 */
function cleanNodeLabel(label: string): string {
  console.debug('[MermaidParser] 开始清理节点标签:', label);
  
  try {
    if (typeof label !== 'string') {
      console.error('[MermaidParser] 清理节点标签失败: 输入不是字符串');
      throw new Error('Invalid input: label must be a string');
    }

    if (!label.trim()) {
      console.debug('[MermaidParser] 空标签内容，返回空字符串');
      return '';
    }

    let cleaned = label;
    
    // 处理根节点的括号语法 root(文本)
    if (cleaned.startsWith('root(') && cleaned.endsWith(')')) {
      cleaned = cleaned.substring(5, cleaned.length - 1).trim();
      console.debug('[MermaidParser] 处理根节点标签后:', cleaned);
    }

    // 移除::注释及其参数
    cleaned = cleaned.replace(/::(?:\w+)(?:\([^)]*\))?/g, '');
    console.debug('[MermaidParser] 移除注释后:', cleaned);

    // 移除emoji和装饰性字符
    cleaned = cleaned
      .replace(/[\u{1F000}-\u{1FFFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{FE00}-\u{FEFF}]/gu, '')
      .replace(/[\u0000-\u001F\u007F-\u009F]/g, '')
      .replace(/[\u200B-\u200D\uFEFF]/g, '')
      .replace(/[❤️🔴🟢🚩🛠️🔬📈]/g, '')
      .trim();
    console.debug('[MermaidParser] 移除特殊字符后:', cleaned);

    // 如果清理后为空，使用默认文本
    if (!cleaned) {
      console.warn('[MermaidParser] 清理后标签为空，使用默认文本');
      cleaned = '未命名节点';
    }
    
    console.debug('[MermaidParser] 最终清理结果:', cleaned);
    return cleaned;
    
  } catch (error) {
    console.error('[MermaidParser] 清理节点标签时发生错误:', error);
    // 返回一个安全的默认值
    return '错误的节点标签';
  }
}

/**
 * 将树形结构转换为思维导图数据格式
 * @param {TreeNode} node 树形结构的节点
 * @param {number} level 节点层级
 * @returns {MindMapData} 思维导图数据格式
 */
export function convertToMindMapData(node: TreeNode, level: number = 0): MindMapData {
  console.debug('[MermaidParser] 开始转换节点到思维导图数据:', { id: node.id, label: node.label, level });
  
  try {
    if (!node || typeof node !== 'object') {
      console.error('[MermaidParser] 无效的节点输入');
      throw new Error('Invalid node input');
    }

    // 根据层级确定节点类型
    let type: 'topic' | 'topic-branch' | 'topic-child' = 'topic';
    if (level === 1) {
      type = 'topic-branch';
    } else if (level > 1) {
      type = 'topic-child';
    }
    console.debug('[MermaidParser] 确定节点类型:', type);

    // 根据节点类型设置宽高，可根据标签长度动态调整
    let width = Math.max(160, 20 + node.label.length * 8);
    let height = 50;
    
    if (type === 'topic-branch') {
      width = Math.max(100, 15 + node.label.length * 6);
      height = 40;
    } else if (type === 'topic-child') {
      width = Math.max(60, 10 + node.label.length * 5);
      height = 30;
    }
    console.debug('[MermaidParser] 计算节点尺寸:', { width, height });

    const result: MindMapData = {
      id: node.id,
      type,
      label: node.label,
      width,
      height
    };

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      console.debug('[MermaidParser] 处理子节点，数量:', node.children.length);
      result.children = node.children.map(child => {
        try {
          return convertToMindMapData(child, level + 1);
        } catch (error) {
          console.error('[MermaidParser] 转换子节点时出错:', error);
          // 返回一个错误节点作为回退
          return {
            id: `error-${child.id}`,
            type: 'topic-child',
            label: '转换错误',
            width: 100,
            height: 30,
            children: []
          };
        }
      });
    }

    console.debug('[MermaidParser] 节点转换完成:', { 
      id: result.id,
      label: result.label,
      childrenCount: result.children ? result.children.length : 0
    });
    return result;
    
  } catch (error) {
    console.error('[MermaidParser] 转换节点到思维导图数据时发生错误:', error);
    // 返回一个错误节点作为回退
    return {
      id: 'error-node',
      type: 'topic',
      label: '转换错误',
      width: 160,
      height: 50,
      children: []
    };
  }
}

export function mermaidToMindMap(mermaidText: string): MindMapData {
  console.debug('[MermaidParser] 开始将Mermaid文本转换为思维导图数据');
  console.time('[MermaidParser] mermaidToMindMap执行时间');
  
  try {
    // 输入验证
    if (!mermaidText || typeof mermaidText !== 'string') {
      console.error('[MermaidParser] 无效的输入: mermaidText为空或不是字符串');
      throw new Error('Invalid input: Mermaid text must be a non-empty string');
    }

    // 解析为树形结构
    console.debug('[MermaidParser] 开始解析Mermaid文本为树形结构');
    const treeNode = parseMermaidToTree(mermaidText);
    console.debug('[MermaidParser] 树形结构解析完成');

    // 转换为思维导图数据
    console.debug('[MermaidParser] 开始转换树形结构为思维导图数据');
    const result = convertToMindMapData(treeNode);
    console.debug('[MermaidParser] 思维导图数据转换完成');

    console.timeEnd('[MermaidParser] mermaidToMindMap执行时间');
    return result;
    
  } catch (error) {
    console.error('[MermaidParser] 转换Mermaid文本为思维导图数据时发生错误:', error);
    console.timeEnd('[MermaidParser] mermaidToMindMap执行时间');
    
    // 返回一个错误节点作为回退
    return {
      id: 'error-root',
      type: 'topic',
      label: '解析错误',
      width: 160,
      height: 50,
      children: [{
        id: 'error-details',
        type: 'topic-child',
        label: error instanceof Error ? error.message : '未知解析错误',
        width: 200,
        height: 40
      }]
    };
  }
}